package com.tiantianyuegou.database.dao;


import android.content.Context;
import com.j256.ormlite.dao.Dao;
import com.tiantianyuegou.database.DatabaseHelper;
import com.tiantianyuegou.database.SearchHistory;
import java.sql.SQLException;
import java.util.List;


/**
 * 
 *@Title:搜索历史dao类
 *@Description:
 *@Author:trouble
 *@Since:2015-9-5
 *@Version:1.1.0
 */
public class SearchHistoryDao {

	private Dao<SearchHistory, Integer> dao;

	private static SearchHistoryDao instance;

	public static SearchHistoryDao getInstance(Context context) {
		if (instance == null) {
			synchronized (SearchHistoryDao.class) {
				if (instance == null)
					instance = new SearchHistoryDao(null);
			}
		}
		return instance;
	}

	private SearchHistoryDao() {

	}

	private SearchHistoryDao(Context context) {
		DatabaseHelper helper = DatabaseHelper.getInstance();
		try {
			dao = helper.getDao(SearchHistory.class);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 插入搜索记录
	 * @param history
	 * @Description:
	 */
	public void insert(SearchHistory history) {
		try {
			dao.create(history);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 插入搜索记录
	 * @param history
	 * @Description:
	 */
	public void insert(String history) {
		SearchHistory searchHistory = new SearchHistory();
		searchHistory.content = history;
		searchHistory.createTime = System.currentTimeMillis();
		insert(searchHistory);
	}

	/**
	 * 读取搜索记录
	 */

	public List<SearchHistory> queryHistory() {
		try {
			return dao.queryBuilder().distinct().selectColumns("content").query();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 读取最后搜索记录
	 * @return
	 * @Description:
	 */
	public SearchHistory queryLastHistory() {
		try {
			return dao.queryBuilder().queryForFirst();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 清空搜索记录
	 * 
	 * @Description:
	 */
	public void delete() {
		try {
			dao.deleteBuilder().delete();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
